package com.indictor.controller;

import com.indicator.base.constant.ControllerConstants;
import com.indictor.conf.RedisConfig;
import com.indictor.controller.parameter.IndicatorParameter;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.indicator.base.constant.ControllerConstants.*;


@RestController()
@RequestMapping(INDICATOR)
public class IndicatorController {

//    @PostMapping(ControllerConstants.ADD)
//    public String addIndicator(@RequestBody IndicatorParameter indicatorParameter) {
//        RedisCommands redisCommands = RedisConfig.getInstance().get();
//        Object obj = redisCommands.get(indicatorParameter.getKey());
//        if (obj == null) {
//            redisCommands.set(indicatorParameter.getKey(), indicatorParameter.getValue());
//            return ControllerConstants.OK;
//        }
//        return ControllerConstants.EXITS;
//    }

    /**
     * 通知到订阅的客户端
     * @param indicatorParameter
     * @return
     */
    @PostMapping(ControllerConstants.UPDATE)
    public String updateIndictor(@RequestBody IndicatorParameter indicatorParameter) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        redisCommands.hset(INDICATOR_REDIS+indicatorParameter.getKey(), COMPUTE_TYPE_KEY, indicatorParameter.getType());
        redisCommands.hset(INDICATOR_REDIS+indicatorParameter.getKey(), COMPUTE_TYPE_DEFAULT_VALUE, indicatorParameter.getValue());
        redisCommands.hset(INDICATOR_REDIS+indicatorParameter.getKey(), IS_COMPUTE, indicatorParameter.getIsCompute());
        redisCommands.hset(INDICATOR_REDIS+indicatorParameter.getKey(), COMPUTE_SUB_KEY, indicatorParameter.getKey());
        return ControllerConstants.OK;
    }

    @DeleteMapping(ControllerConstants.DELETE + DIAGONAL + KEY+"/{subKey}")
    public String deleteIndictor(@PathVariable String key,@PathVariable String subKey) {
        if(subKey.equals("-1")){
            RedisConfig.getInstance().get().zrem(key);
        }else {
            RedisConfig.getInstance().get().zrem(key,subKey);
        }
        return ControllerConstants.OK;
    }

    @GetMapping(ControllerConstants.GET + DIAGONAL + KEY)
    public Map<String, Object> getIndictor(@PathVariable String key) {
        return RedisConfig.getInstance().get().hgetall(key);
    }

}
